package com.yinhai.modules.security.spring.app.handler;

import com.yinhai.core.app.api.util.WebUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by yanglq on 2018/12/27 0027.
 * 自定义权限不足的处理
 * 添加针对ajax等异步请求 返回信息（原handle只支持页面请求的权限不足返回）
 */
public class TaAccessDeniedHandler implements AccessDeniedHandler {
    protected static final Log logger = LogFactory.getLog(TaAccessDeniedHandler.class);
    private String errorPage;

    public TaAccessDeniedHandler() {
    }

    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        if(!response.isCommitted()) {
            //异步请求
            if(WebUtil.isAjaxRequest(request)){
                String defaultJsonMessage="{\"success\":\"false\",\"msg\":\""+accessDeniedException.getMessage()+"\",\"jsonperror\":\"true\"}";
                response.setStatus(403);
                response.setContentType("text/json; charset=UTF-8"); //解决从服务器返回中文乱码问题
                PrintWriter writer = response.getWriter();
                writer.write(defaultJsonMessage);
                writer.flush();
//                response.sendError(403, accessDeniedException.getMessage());
            }
            else if(this.errorPage != null) {
                request.setAttribute("SPRING_SECURITY_403_EXCEPTION", accessDeniedException);
                response.setStatus(403);
                RequestDispatcher dispatcher = request.getRequestDispatcher(this.errorPage);
                dispatcher.forward(request, response);
            } else {
                response.sendError(403, accessDeniedException.getMessage());
            }
        }

    }

    public void setErrorPage(String errorPage) {
        if(errorPage != null && !errorPage.startsWith("/")) {
            throw new IllegalArgumentException("errorPage must begin with '/'");
        } else {
            this.errorPage = errorPage;
        }
    }
}
